package com.magicborrow.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.adapter.BorrowReceiveAdapter;
import com.magicborrow.beans.ApplyEntity;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import java.util.ArrayList;
import java.util.HashMap;

public class BorrowReceiveFragment extends Fragment implements VolleyTool.HTTPListener{

    private RelativeLayout mFragmentLayout;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRefreshRecyclerView;
    private View mFootView;
    private LinearLayoutManager mLinearLayoutManager;
    private BorrowReceiveAdapter mBorrowReceiveAdapter;
    private ArrayList<ApplyEntity.ContentData> mData;
    private int page = 0;
    private int size = 10;
    private boolean lastPage = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mFragmentLayout = (RelativeLayout) inflater.inflate(R.layout.borrow_receive_fragment,null);
        initView();
        initListener();
        initData();
        sendRequest();
        return mFragmentLayout;
    }

    private void initView(){
        mSwipeRefreshLayout = (SwipeRefreshLayout)mFragmentLayout.findViewById(R.id.swipeRefreshLayout);
        mRefreshRecyclerView = (RecyclerView)mFragmentLayout.findViewById(R.id.recyclerView);
        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRefreshRecyclerView.setLayoutManager(mLinearLayoutManager);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.title_color,
                R.color.title_color, R.color.title_color,
                R.color.title_color);
    }

    private void initListener() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                lastPage = false;
                sendRequest();
            }
        });
        mRefreshRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLinearLayoutManager.findLastVisibleItemPosition() + 1 == mBorrowReceiveAdapter.getItemCount()) {
                    if(lastPage){return;}
                    showFootview(true);
                    page++;
                    sendRequest();
                }
            }
        });
    }

    private void initData() {
        mData = new ArrayList<>();
        mBorrowReceiveAdapter = new BorrowReceiveAdapter(getActivity());
        mBorrowReceiveAdapter.setData(mData);
        mRefreshRecyclerView.setAdapter(mBorrowReceiveAdapter);
    }

    private void sendRequest(){
        HashMap<String,String> params = new HashMap<>();
        params.put("borrow", "true");
        params.put("acc_token", UserTools.getUser(getActivity()).getAcc_token());
        params.put("page",page+"");
        params.put("size",size+"");
        VolleyTool.get(Constants.I_BORROW_URL, params, this, 0, ApplyEntity.class);
    }

    private void showFootview(boolean isVis){
        if(mFootView == null){
            mFootView = mRefreshRecyclerView.findViewWithTag("foot");
        }
        TextView tv = (TextView) mFootView.findViewById(R.id.no_more_textView);
        ProgressBar bar = (ProgressBar) mFootView.findViewById(R.id.load_more_progressBar);
        if(isVis){
            bar.setVisibility(View.VISIBLE);
            tv.setText("正在加载...");
        }else{
            bar.setVisibility(View.GONE);
            tv.setText("没有更多了");
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if(requestCode == 0) {
            ApplyEntity bean = (ApplyEntity) t;
            if (bean.getCode() == 0) {
                if (page == 0) {
                    if (mSwipeRefreshLayout.isShown()) {
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    mBorrowReceiveAdapter.getData().clear();
                    mData.addAll(bean.getData().getContent());
                    mBorrowReceiveAdapter.notifyDataSetChanged();
                    if(bean.getData().getContent().size() < 10){
                        showFootview(false);
                    }
                } else {
                    if (bean.getData().getContent().size() > 0) {
                        int startPosition = mBorrowReceiveAdapter.getItemCount();
                        mBorrowReceiveAdapter.getData().addAll(bean.getData().getContent());
                        mBorrowReceiveAdapter.notifyItemRangeInserted(startPosition, bean.getData().getContent().size());
                        if(bean.getData().getContent().size() < 10){
                            showFootview(false);
                        }
                    } else {
                        lastPage = true;
                        showFootview(false);
                    }
                }
            } else {
                Toast.makeText(getActivity(),bean.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        Toast.makeText(getActivity(),"服务器暂时无法连接",Toast.LENGTH_SHORT).show();
    }

}
